/**
 * @file 表格插件
 * @desc 表格数据均为异步加载，支持查询事件
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */
layui.define(['table', 'layer'], function (exports) {
    var $ = layui.$;
    var table = layui.table;
    var layer = layui.layer;

    var tableInstance = null;
    var sortLoad = null;
    var search = null;
    var refresh = null;

    var defaultConfig = {
        elem: '',
        url: '/',
        method: 'GET',
        where: {
        },
        loading: true,
        page: true,
        limit: 50,
        autoSort: false, // 服务端获取排序数据
        parseData: function (res) {
            return {
                "code": res.status, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.data.count, //解析数据长度
                "data": res.data.data //解析数据列表
            };
        },
        request: {
            pageName: 'pageIndex', // 页码
            limitName: 'pageSize' // 条数限制
        },
        response: {
            statusCode: 200
        },
        initSort: {
        },
        cols: []
    };

    function normalizeConfig (config) {
        return Object.assign({}, defaultConfig, config);
    }

    function beforeRender () {
        layer.closeAll();
    }

    function renderTable (config) {
        beforeRender();
        return table.render(config);
    }

    function reloadTable (id, config) {
        beforeRender();
        return table.reload(id, config);
    }

    function createSortLoadFunc (id) {
        return function (obj) {
            beforeRender();
            /**
             * 排序：
             * type:
             * asc 升序 1
             * desc 降序 2
             */
            var params = {
                orderField: obj.field,
                defaultOrder: obj.type === 'asc' ? 1 : 2
            };

            table.reload(id, {
                initSort: obj,
                where: params,
                page: {
                    curr: 1
                }
            });
        }
    }

    function createSearchFunc (id) {
        return function(params) {
            beforeRender();
            table.reload(id, {
                where: params,
                page: {
                    curr: 1
                }
            });
        }
    }

    function createRefreshFunc (id) {
        return function() {
            beforeRender();
            table.reload(id);
        }
    }

    /**
     * 初始化页面事件
     */
    function initEvent (tableFilter) {
        // 监听表格排序字段点击
        table.on('sort(' + tableFilter + ')', function (obj) {
            sortLoad(obj);
        });
    }

    /**
     * 初始化页面
     */
    function init (externalOptions) {
        var config = externalOptions.config;
        var tableFilter = externalOptions.filter;
        var eventRegister = externalOptions.event;

        var id =  config.id;
        var options = normalizeConfig(config);

        sortLoad = createSortLoadFunc(id);
        search = createSearchFunc(id);
        refresh = createRefreshFunc(id);

        // 渲染 table
        tableInstance = renderTable(options);

        // 初始化页面事件
        initEvent(tableFilter);
        if (eventRegister && typeof eventRegister === 'function') {
            eventRegister();
        }

        return {
            refresh: refresh,
            search: search,
            tableInstance: tableInstance
        };
    }

    /**
     * 重载数据表格
     */
    function reload (externalOptions) {
        var config = externalOptions.config;
        var tableFilter = externalOptions.filter;
        var eventRegister = externalOptions.event;

        var id =  config.id;
        var options = normalizeConfig(config);

        sortLoad = createSortLoadFunc(id);
        search = createSearchFunc(id);
        refresh = createRefreshFunc(id);

        reloadTable(id, options);

        // 初始化页面事件
        initEvent(tableFilter);
        if (eventRegister && typeof eventRegister === 'function') {
            eventRegister();
        }
    }

    exports('zmnTable', {
        init: init,
        reload: reload
    });
});